package com.coolrui.domain.user.repository.impl;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.coolrui.common.system.ApiList;
import com.coolrui.common.utils.CommonUtils;
import com.coolrui.domain.user.entity.UserAccount;
import com.coolrui.domain.user.mapper.UserMapper;
import com.coolrui.domain.user.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserRepositoryImpl implements UserRepository {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserAccount getUser(Long userId) {
        return userMapper.selectById(userId);
    }

    @Override
    public List<UserAccount> getUserList(Integer page, Integer pageSize) {
        LambdaQueryWrapper<UserAccount> wrapper = Wrappers.lambdaQuery();
        wrapper.last(CommonUtils.getLimitSql(page, pageSize,false));
        return userMapper.selectList(wrapper);
    }

    @Override
    public ApiList<UserAccount> getUserList(Long cityId, Integer page, Integer pageSize) {
        LambdaQueryWrapper<UserAccount> wrapper = Wrappers.lambdaQuery();
        //根据条件查询
        if (cityId > 0) {
            wrapper.eq(UserAccount::getCityId, cityId);
        }
        //设置分页SQL
        wrapper.last(CommonUtils.getLimitSql(page, pageSize,true));
        //执行查询
        List<UserAccount> list = userMapper.selectList(wrapper);
        //API接口优化：是否存在下一页
        boolean hasMore = list.size() > pageSize;
        if (hasMore) {
            list = ListUtil.sub(list, 0, pageSize);
        }
        return ApiList.makeResult(hasMore, list);
    }

    @Override
    public int createUser(UserAccount user) {
        return userMapper.insert(user);
    }
}
